package com.myhome.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.dto.UserDto;
import com.myhome.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myhome.domain.WorkIssue;
import com.myhome.mapper.WorkIssueMapper;
import com.myhome.service.WorkIssueService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author QYiXin
 * @Date 2021 10 09 12 58
 **/
@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService {
    @Autowired
    UserFeign userFeign;

    @Override
    public Page<WorkIssue> findByPage(Page<WorkIssue> page, Integer status, String startTime, String endTime) {
        Page<WorkIssue> workIssues = page(page, new LambdaQueryWrapper<WorkIssue>()
                .eq(status != null, WorkIssue::getStatus, status)
                .between(
                        (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)),
                        WorkIssue::getCreated,
                        startTime, endTime + " 23:59:59")
        );
        List<WorkIssue> result = workIssues.getRecords();
        if (CollectionUtil.isEmpty(result)) {
            return workIssues;
        }
        List<Long> ids = result.stream().map(WorkIssue::getUserId).collect(Collectors.toList());
        List<UserDto> basicUsers = userFeign.getBasicUsers(ids);
        Map<Long, UserDto> userDtoMap = basicUsers.stream().collect(Collectors.toMap(UserDto::getId, userDto -> userDto));
        if (!ObjectUtils.isEmpty(result)) {
            result.forEach(one -> {
                UserDto userDto = userDtoMap.get(one.getUserId());
                if (userDto != null) {
                    one.setRealName(userDto.getRealName());
                    one.setUsername(userDto.getUsername());
                }
                /*one.setRealName(userDto.getRealName());
                one.setUsername(userDto.getUsername());*/
            });
        }
        return workIssues;
    }

    @Override
    public Page<WorkIssue> getIssueList(Page<WorkIssue> page,Long userId) {
        return this.page(page, new LambdaQueryWrapper<WorkIssue>().eq(userId != null, WorkIssue::getUserId, userId));
    }
}
